package com.zige.zige.activity.videoplay;

import android.annotation.SuppressLint;
import android.app.AlertDialog.Builder;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.MotionEventCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.zige.zige.R;
import com.zige.zige.activity.BaseActivity;
import com.zige.zige.bj_vr.BJVrPlayActivity;
import com.zige.zige.constants.Constants;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.dialog.PromptDialog;
import com.zige.zige.dialog.ZiGeShareDialog;
import com.zige.zige.operationgudie.ScreenOperateDialog;
import com.zige.zige.operationgudie.SlidingAroundOperateDialog;
import com.zige.zige.pojo.UserInfo;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.PreferencesUtils;
import com.zige.zige.utils.SharedPreferencesUtils;
import com.zige.zige.utils.SystemUtils;
import com.zige.zige.utils.ToastUtils;
import com.zige.zige.utils.VolleyImageUtils;
import com.zige.zige.view.Controller;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

public class ActivityVideodetailActivity extends BaseActivity implements OnClickListener {
    MediaPlayer mPlayer;
    SurfaceView mSurfaceView;
    Controller mController;
    OnClickListener next, prev, mFullScreen;
    SurfaceHolder.Callback mCallback;
    OnPreparedListener mPreparedListener;
    Controller.ControlOper mPlayerControl;


    private FrameLayout videoWrap;
    private TextView videoTitleTv, publisherTv, videoContextTv;
    private ImageView zanBtn, shareBtn, imgf_video_index, img_loading;
    private LinearLayout lay_others, loading_lyt;


    private String jxVideoId, praisecount;
    private int isPraises;
    private String videoTitle, videoContext, videoImageUrl;
    private UserInfo userInfo;

    private TextView tv_prise_count;
    private String mVideoUrl;

    private int oldHeight;
    private int mSize;

    /***
     * 横竖屏初始化
     *
     * @param savedInstanceState
     */
    private int screenWidth;
    private int screenHeight;
    private boolean sensor_flag = true;
    private boolean stretch_flag = true;
    private boolean isMyScreen;
    private SensorManager sm;
    private OrientationSensorListener listener;
    private Sensor sensor;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 888:
                    int orientation = msg.arg1;
                    if (orientation > 45 && orientation < 135) {

                    } else if (orientation > 135 && orientation < 225) {

                    } else if (orientation > 225 && orientation < 315) {
                        System.out.println("切换成横屏");
                        ActivityVideodetailActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        sensor_flag = false;
                        stretch_flag = false;
                        isMyScreen = false;
                    } else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) {
                        System.out.println("切换成竖屏");
                        isMyScreen = true;
                        ActivityVideodetailActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                        sensor_flag = true;
                        stretch_flag = true;

                    }
                    break;
                default:
                    break;
            }

        }

        ;
    };
    private SensorManager sm1;
    private Sensor sensor1;
    private OrientationSensorListener2 listener1;
    public boolean record_flag;
    private FrameLayout vrPlayer;

    private FrameLayout lay_normal_video;
    /***
     * VR视频
     **/
    private ImageView img_videodetails_bg, img_lay_bg, img_video_play;//视频图片背景、大背景
    private LinearLayout lay_backed;
    private RelativeLayout lay_vr_video;
    private TextView tv_vr_title;
    private LinearLayout lay_back,lat_text_title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        screenWidth = display.getWidth();
        screenHeight = display.getHeight();
        setContentView(R.layout.activity_activityvideodetails);
        registAccelerometer();
        userInfo = application.getUserInfo();
        findView();
        imgf_video_index.setVisibility(View.INVISIBLE);
        mPlayer = new MediaPlayer();
        mController = new Controller(ActivityVideodetailActivity.this);
        initlistener();
        initSerface();
        mController.setPrevNextListeners(next, prev, mFullScreen, null, null);
        alert = new Builder(this);
        MyAsync task = new MyAsync();
        task.execute(getIntent());

//        showOperateDialog();
        userSetPraises();
        screenState();
        FrameLayout vrPlayer = (FrameLayout) findViewById(R.id.lay_normal_video);
        ViewGroup.LayoutParams oldParams = vrPlayer.getLayoutParams();
        oldHeight = oldParams.height;
    }

    private void findView() {
        SharedPreferencesUtils.getValue(mContext,SharedPreferencesUtils.user_isWatch,true);
        lay_back =  serchViewById(R.id.lay_back);
        lay_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        lat_text_title = serchViewById(R.id.lat_text_title);
        /***VR*--start-**/
        tv_vr_title = serchViewById(R.id.tv_vr_title);
        img_video_play = serchViewById(R.id.img_video_play);
        img_video_play.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("videoId", jxVideoId);
                intent.setClass(ActivityVideodetailActivity.this, BJVrPlayActivity.class);
                startActivity(intent);
            }
        });
        lay_backed = serchViewById(R.id.lay_vr_backed);
        lay_backed.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        img_videodetails_bg = serchViewById(R.id.img_videodetails_bg);
        img_lay_bg = serchViewById(R.id.img_vr_bg);
        lay_vr_video = serchViewById(R.id.lay_vr_video);
        loading_lyt = serchViewById(R.id.loading_lyt);
        img_loading = (ImageView)findViewById(R.id.img_loading);
        /****VR*--end
         * -*****/
        lay_normal_video = serchViewById(R.id.lay_normal_video);
        vrPlayer = (FrameLayout) findViewById(R.id.surfacecontainer);
        tv_prise_count = serchViewById(R.id.tv_prise_count);
        videoTitleTv = findViewByIds(R.id.video_title);
        publisherTv = findViewByIds(R.id.publisher);
        videoContextTv = findViewByIds(R.id.video_context);
        videoContextTv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //继承了Activity的onTouchEvent方法，直接监听点击事件
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    //当手指按下的时候
                    x1 = event.getX();
                    y1 = event.getY();
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    //当手指离开的时候
                    x2 = event.getX();
                    y2 = event.getY();
                    if ((y1 - y2 > 50) && (Math.abs(x2 - x1) <= (y1 - y2))) {
                    } else if ((y2 - y1 > 50) && (Math.abs(x2 - x1) <= (y2 - y1))) {
                    } else if ((x1 - x2 > 50) && (Math.abs(y2 - y1) < (x1 - x2))) {

                    } else if ((x2 - x1 > 50) && (Math.abs(y2 - y1) < (x2 - x1))) {
                    }
                }
                return true;
            }
        });
        shareBtn = findViewByIds(R.id.img_share);
        shareBtn.setOnClickListener(this);
        lay_others = serchViewById(R.id.lay_others);
        imgf_video_index = serchViewById(R.id.imgf_video_index);
    }


    private void registAccelerometer() {
        //注册重力感应器  屏幕旋转
        sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        listener = new OrientationSensorListener(handler);
        sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
        //根据  旋转之后 点击 符合之后 激活sm
        sm1 = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor1 = sm1.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        listener1 = new OrientationSensorListener2();
        sm1.registerListener(listener1, sensor1, SensorManager.SENSOR_DELAY_UI);
    }

    private void initSerface() {
        initListeners();
        mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview);
        // mSurfaceView.setZOrderOnTop(true);
        // mSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        mSurfaceView.setVisibility(View.GONE);
        SurfaceHolder surfaceHolder = mSurfaceView.getHolder();
        surfaceHolder.addCallback(mCallback);
    }


    private void showOperateDialog() {
        boolean isShow = (boolean) SharedPreferencesUtils.getValue(ActivityVideodetailActivity.this, SharedPreferencesUtils.videodetails_operate_guide, false);
        if (!isShow) {
            ScreenOperateDialog dialog1 = new ScreenOperateDialog();
            dialog1.show(getSupportFragmentManager(), "");
            SlidingAroundOperateDialog dialog = new SlidingAroundOperateDialog();
            dialog.show(getSupportFragmentManager(), "");
        }
    }


    private void playVideo(String videourl, String vid) {

        if (application.isLogin()) {
            userWatchRecord(vid);
        }
        try {
            mPlayer.reset();
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.setDataSource(this, Uri.parse(videourl));
            mPlayer.setOnPreparedListener(mPreparedListener);
            mPlayer.prepareAsync();
//            if (mPlayer.isPlaying()) {
//                closeLoadingDialog();
//            }
            mPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    if (percent <= 100 && percent > 0)
                        mSurfaceView.setVisibility(View.VISIBLE);

                }

            });
            mPlayer.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
//                    if (!finish &&videoType==0)
//                        onNext();
                }
            });
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    void initlistener() {
        next = new OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        };
        prev = new OnClickListener() {

            @Override
            public void onClick(View v) {
            }
        };
        mFullScreen = new OnClickListener() {
            @Override
            public void onClick(View v) {
                sm.unregisterListener(listener);
                if (stretch_flag) {
                    stretch_flag = false;
                    //切换成横屏
                    isMyScreen = true;
//                    mController.mBtnFullscreen.setImageResource(R.drawable.exit_full);
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    RelativeLayout video_discussion = (RelativeLayout) findViewById(R.id.video_discussion);
                    video_discussion.setVisibility(View.GONE);
                    FrameLayout vrPlayer = (FrameLayout) findViewById(R.id.surfacecontainer);
                    ViewGroup.LayoutParams Params = vrPlayer.getLayoutParams();
                    Params.height = ((LinearLayout) findViewById(R.id.activity_vr_videodetail_dock)).getLayoutParams().height;
                } else {
                    stretch_flag = true;
                    isMyScreen = false;
                    //切换成竖屏
//                    mController.mBtnFullscreen.setImageResource(R.drawable.enter_full);
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    FrameLayout vrPlayer = (FrameLayout) findViewById(R.id.surfacecontainer);
                    ViewGroup.LayoutParams Params = vrPlayer.getLayoutParams();
                    Params.height = oldHeight;
                    RelativeLayout video_discussion = (RelativeLayout) findViewById(R.id.video_discussion);
                    video_discussion.setVisibility(View.VISIBLE);

                }


            }
        };

    }


    int videoType = 3;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (videoType == 0) {
            if (stretch_flag) {
                //切换成竖屏;
                isMyScreen = false;
//            mController.mBtnFullscreen.setImageResource(R.drawable.enter_full);
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                FrameLayout vrPlayer = (FrameLayout) findViewById(R.id.lay_normal_video);
                ViewGroup.LayoutParams Params = vrPlayer.getLayoutParams();
                Params.height = oldHeight;
                RelativeLayout video_discussion = (RelativeLayout) findViewById(R.id.video_discussion);
                video_discussion.setVisibility(View.VISIBLE);

            } else {
                //切换成横屏
                isMyScreen = true;
//            mController.mBtnFullscreen.setImageResource(R.drawable.exit_full);
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                RelativeLayout video_discussion = (RelativeLayout) findViewById(R.id.video_discussion);
                video_discussion.setVisibility(View.GONE);
                FrameLayout vrPlayer = (FrameLayout) findViewById(R.id.lay_normal_video);
                ViewGroup.LayoutParams Params = vrPlayer.getLayoutParams();
                Params.height = ((LinearLayout) findViewById(R.id.activity_vr_videodetail_dock)).getLayoutParams().height;

            }
        } else {
            isMyScreen = false;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

    }

    private void screenState() {
        KeyguardManager mKeyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
        boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode();
        if (flag) {
            return;
        } else {
            mPlayerControl.pause();

        }
    }

    //手指按下的点为(x1, y1)手指离开屏幕的点为(x2, y2)
    float x1 = 0;
    float x2 = 0;
    float y1 = 0;
    float y2 = 0;


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    private void userSetPraises() {
        zanBtn = findViewByIds(R.id.zan_btn);
        zanBtn.setImageResource(R.drawable.user_prise);
        zanBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (application.isLogin()) {
                    setPressPraise(operate);
                } else {
                    PromptDialog dialog = new PromptDialog();
                    dialog.show(getFragmentManager(), "dialo");
                }

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_share:
                mPlayerControl.pause();
                sharesina();
                break;
        }
    }

    //    private AnimationDrawable animation;
    @Override
    public void closeLoadingDialog() {
        loading_lyt.setVisibility(View.GONE);
    }

    @Override
    public void showLoadingDialog() {
        loading_lyt.setVisibility(View.VISIBLE);
        loading_lyt.setEnabled(false);
        img_loading.setBackgroundResource(R.drawable.being_loaded);
        AnimationDrawable animation = (AnimationDrawable) img_loading.getBackground();
        animation.start();
    }


    String shareImageUrl;

    private void getVideoDetils(String vid) {
        String uid;
        if (application.isLogin()) {
            uid = application.getUserInfo().userID;
        } else {
            uid = "";
        }
        Log.e("wu","活动视频   "+uid);
        HashMap<String, String> params = new HashMap<>();
        params.put("vid", vid);
        params.put("userId", uid);
        showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(params, ActivityVideodetailActivity.this, UrlConsts.VIDEO_DETILS) {
            @Override
            protected void handleResponse(String response) {
                Log.e("wu","    h活动视频返回  "+response);
                try {
                    JSONObject object = new JSONObject(response);
                    int ret = object.getInt("code");
                    String msg = object.getString("message");
                    if (ret == 0000) {
                        object = object.getJSONObject("jxVideo");
                        jxVideoId = object.getString("id");
                        videoTitle = object.getString("videoName");
                        videoTitleTv.setText(videoTitle);
                        publisherTv.setText("推荐人：" + object.getString("referrer"));
                        videoContext = object.getString("videoDesc");
                        videoContextTv.setText(videoContext);
                        videoImageUrl = object.getString("videoPicUrl");
                        shareImageUrl = object.getString("sharePicUrl");
                        videoType = object.getInt("videoType");
                        isPraises = object.getInt("praised");
                        if (application.isLogin()) {
                            if (isPraises == 1) {
                                operate = 1;
                                zanBtn.setImageResource(R.drawable.zan_selected);
                            } else {
                                zanBtn.setImageResource(R.drawable.user_prise);
                                operate = 0;
                            }
                        } else {
                            zanBtn.setImageResource(R.drawable.user_prise);
                        }
                        Log.e("wu","   ****  "+object.getString("praiseCount"));
                        opreatePriess(object.getString("praiseCount"));
//                        showOperateDialog(videoType);
                        isVRVideo(object.getInt("videoType"));
                        if (object.getInt("videoType") == 1) {
                            ActivityVideodetailActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                            VolleyImageUtils.displayImage(videoImageUrl, img_videodetails_bg, ActivityVideodetailActivity.this);
                            VolleyImageUtils.displayImage(videoImageUrl, img_lay_bg, ActivityVideodetailActivity.this);
                            videoTitleTv.setVisibility(View.VISIBLE);
                            mVideoUrl = null;
                            videoTitleTv.setText("剧情介绍");
                            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

                        } else if (videoType == 0) {
                            videoTitleTv.setVisibility(View.VISIBLE);
                            mVideoUrl = object.getString("videoUrl");
                        }
                        playVideo(mVideoUrl, jxVideoId);



                    } else {
                        throw new Exception(msg);
                    }
                } catch (Exception e) {
                    closeLoadingDialog();
                } finally {
//                    closeLoadingDialog();
                }
            }

            @Override
            protected void handleError() {
                super.handleError();
                closeLoadingDialog();
            }
        });
    }

    private void opreatePriess(String praiseCount){

        if (praiseCount == null || praiseCount.toString().equals("null")) {
            tv_prise_count.setText(0);
            one = 1;
        } else {
            one = Integer.parseInt(praiseCount);
            tv_prise_count.setText(praiseCount);
        }

    }

    int one;

    int operate;

    private void setPressPraise(final int operated) {
        String deviceId = SystemUtils.getDeviceKey(ActivityVideodetailActivity.this);
        HashMap<String, String> params = new HashMap<>();
        params.put("deviceId", deviceId);
        params.put("uid", application.getUserInfo().userID);
        params.put("account", application.getUserInfo().phoneNumber);
        params.put("jxVideoId", jxVideoId);
        params.put("operate", String.valueOf(operated));
        TaskExecutor.getInstance().execute(new PostRequestTask(params, ActivityVideodetailActivity.this, UrlConsts.VIDEO_PRAISE) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int ret = object.getInt("code");
                    String msg = object.getString("message");
                    if (ret == 0000) {
                        if (operated == 0) {
                            operate = 1;
                            one++;
                            tv_prise_count.setText(String.valueOf(one));
                            zanBtn.setImageResource(R.drawable.zan_selected);
                        }
                        if (operated == 1) {
                            operate = 0;
                            one--;
                            tv_prise_count.setText(String.valueOf(one));
                            zanBtn.setImageResource(R.drawable.user_prise);
                        }
                    } else {
                        throw new Exception(msg);
                    }
                } catch (Exception e) {
                    showErrorDialog(e.getMessage());
//                    tv_check_error.setVisibility(View.VISIBLE);
                } finally {
                }
            }
        });
    }

    private void userWatchRecord(String videoId) {
        HashMap<String, String> params = new HashMap<>();
        params.put("uid", application.getUserInfo().userID);
        params.put("videoId", videoId);
        TaskExecutor.getInstance().execute(new PostRequestTask(params, ActivityVideodetailActivity.this, UrlConsts.USER_WATCH_RECORD) {
            @Override
            protected void handleResponse(String response) {
            }
        });
    }

    @Override
    protected void onResume() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onResume();
    }

    @Override
    protected void onStop() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onStop();
    }

    private String menuId;
    class MyAsync extends AsyncTask<Intent, Integer, String> {
        @Override
        protected String doInBackground(Intent... params) {
            Intent intent = params[0];
            jxVideoId = intent.getStringExtra("videoId");
            if (jxVideoId == null ) {
                showErrorDialog("无视频数据");
                finish();
            }
            registerReceiver();
            publishProgress(100);
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            if (100 == values[0])
            getVideoDetils(jxVideoId);

            super.onProgressUpdate(values);
        }

    }


    private void isVRVideo(int videoType) {
        if (videoType == 1) {
            //  VR视频
            mPlayer.stop();
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            lay_normal_video.setVisibility(View.GONE);
            lay_vr_video.setVisibility(View.VISIBLE);
            videoTitleTv.setVisibility(View.INVISIBLE);
            if (videoType == 0) {
                tv_vr_title.setText(videoTitle);
            } else {
                tv_vr_title.setText(videoTitle);
            }
        } else if (videoType == 0) {
            //普通视频
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
            lay_vr_video.setVisibility(View.GONE);
            lay_normal_video.setVisibility(View.VISIBLE);
        }
    }

    private void releaseMediaController() {

        mController.removeHandlerCallback();
        releaseMediaPlayer();
        mController = null;
    }

    private void releaseMediaPlayer() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        final int action = MotionEventCompat.getActionMasked(event);

        switch (action) {
            case MotionEvent.ACTION_UP:
                if (mController.isShowing()) {
                    mController.hide();
                } else {
                    mController.show();
                }
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaController();
        unregisterReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPlayerControl.pause();
    }

    boolean finish = false;

    @Override
    public void onBackPressed() {
        finish = true;
        finish();
    }

    private void initListeners() {

        mCallback = new SurfaceHolder.Callback() {

            public void surfaceCreated(SurfaceHolder holder) {
                mPlayer.setDisplay(holder);
            }

            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        };

        mPreparedListener = new OnPreparedListener() {

            @SuppressLint("NewApi")
            public void onPrepared(MediaPlayer mp) {

                mController.setMediaPlayer(mPlayerControl);
                mController.setAnchorView((FrameLayout) findViewById(R.id.lay_normal_video));
                mPlayer.start();
//                int h = mPlayer.getVideoHeight();
//                int w = mPlayer.getVideoWidth();
//
//                DisplayMetrics dm = getResources().getDisplayMetrics();
//                int screenWidth = dm.widthPixels;
//                int screenHeight = dm.heightPixels;
//                if (w > screenWidth || h > screenHeight) {
//                    // 计算出宽高的倍数
//                    float vWidth = (float) w / (float) screenWidth;
//                    float vHeight = (float) h / (float) screenHeight;
//                    // 获取最大的倍数值，按大数值进行缩放
//                    float max = Math.max(vWidth, vHeight);
//                    // 计算出缩放大小,取接近的正值
//                    w = (int) Math.ceil((float) w / max);
//                    h = (int) Math.ceil((float) h / max);
//                } else {
//                    // 计算出宽高的倍数
//                    float vWidth = (float) screenWidth / (float) w;
//                    float vHeight = (float) screenHeight / (float) h;
//                    // 获取最大的倍数值，按大数值进行缩放
//                    float min = Math.min(vWidth, vHeight);
//                    // 计算出缩放大小,取接近的正值
//                    w = (int) Math.ceil((float) w * min);
//                    h = (int) Math.ceil((float) h * min);
//                }
//                LogUtils.i("screen_h=" + screenHeight + "  screen_w=" + screenWidth);
//                LogUtils.i("video_h=" + h + "  video_w=" + w);
//                // 设置SurfaceView的大小并居中显示
//                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(w, h);
//				layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
//				if (currentVideo.getVideoTypeId() != 1)
//					mSurfaceView.setLayoutParams(layoutParams);
//				findViewById(R.id.surface_back).setBackgroundColor(Color.BLACK);
//
//				String backText = currentVideo.getVideoName();
//                mController.setBackText("首页");
//                mController.hideZan();
                mController.hidet();

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        closeLoadingDialog();
                    }
                }, 1000);
            }
        };



        mPlayerControl = new Controller.ControlOper() {

            public void start() {
                mPlayer.start();
            }

            public void pause() {
                mPlayer.pause();
            }

            public int getDuration() {
                return mPlayer.getDuration();
            }

            public int getCurPosition() {
                return mPlayer.getCurrentPosition();
            }

            public void seekTo(int pos) {
                mPlayer.seekTo(pos);
            }

            public boolean isPlaying() {
                return mPlayer.isPlaying();
            }

            public int getBufPercent() {
                return 0;
            }

            public boolean canPause() {
                return true;
            }

            public boolean canSeekBackward() {
                return true;
            }

            public boolean canSeekForward() {
                return true;
            }

            public boolean isFullScreen() {
                return false;
            }

            @Override
            public void showTitle() {

            }

            @Override
            public void hiteTitle() {

            }

            public void fullScreen() {

            }
        };
    }

    NetworkStateChangedReceiver myReceiver;

    private void registerReceiver() {
        boolean isWifiOnly = PreferencesUtils.getBoolean(this, Constants.PREFERENCE_KEY_IS_WIFI_ONLY);
        boolean on = (boolean) SharedPreferencesUtils.getValue(this, SharedPreferencesUtils.gesture_toggle, false);
        if (on || isWifiOnly) {
            return;
        }
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        myReceiver = new NetworkStateChangedReceiver();
        this.registerReceiver(myReceiver, filter);
    }

    private void unregisterReceiver() {
        if (myReceiver != null) {
            this.unregisterReceiver(myReceiver);
            myReceiver = null;
        }
    }

    Builder alert;

    class NetworkStateChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
                ToastUtils.showToast(context, "网络不可以用");
                // 改变背景或者 处理网络的全局变量
            } else if (!wifiNetInfo.isConnected()) {
                mPlayerControl.pause();
                Builder alert = new Builder(context);
                alert.setCancelable(false);
                alert.setTitle("提示");
                alert.setMessage("您正在使用非WIFI网络，播放将产生流量费用");
                alert.setPositiveButton("继续播放", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mPlayerControl.start();
                    }
                }).setNegativeButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mPlayerControl.pause();
                        finish();
                    }
                }).show();
            }

        }

    }


    /**
     * 重力感应监听者
     */
    public class OrientationSensorListener implements SensorEventListener {
        private static final int _DATA_X = 0;
        private static final int _DATA_Y = 1;
        private static final int _DATA_Z = 2;

        public static final int ORIENTATION_UNKNOWN = -1;

        private Handler rotateHandler;

        public OrientationSensorListener(Handler handler) {
            rotateHandler = handler;
        }

        public void onAccuracyChanged(Sensor arg0, int arg1) {
            // TODO Auto-generated method stub

        }

        public void onSensorChanged(SensorEvent event) {

            if (sensor_flag != stretch_flag)  //只有两个不相同才开始监听行为
            {
                float[] values = event.values;
                int orientation = ORIENTATION_UNKNOWN;
                float X = -values[_DATA_X];
                float Y = -values[_DATA_Y];
                float Z = -values[_DATA_Z];
                float magnitude = X * X + Y * Y;
                // Don't trust the angle if the magnitude is small compared to the y value
                if (magnitude * 4 >= Z * Z) {
                    //屏幕旋转时
                    float OneEightyOverPi = 57.29577957855f;
                    float angle = (float) Math.atan2(-Y, X) * OneEightyOverPi;
                    orientation = 90 - (int) Math.round(angle);
                    // normalize to 0 - 359 range
                    while (orientation >= 360) {
                        orientation -= 360;
                    }
                    while (orientation < 0) {
                        orientation += 360;
                    }
                }
                if (rotateHandler != null) {
                    rotateHandler.obtainMessage(888, orientation, 0).sendToTarget();
                }

            }
        }
    }


    public class OrientationSensorListener2 implements SensorEventListener {
        private static final int _DATA_X = 0;
        private static final int _DATA_Y = 1;
        private static final int _DATA_Z = 2;

        public static final int ORIENTATION_UNKNOWN = -1;

        public void onAccuracyChanged(Sensor arg0, int arg1) {
            // TODO Auto-generated method stub

        }

        public void onSensorChanged(SensorEvent event) {

            float[] values = event.values;

            int orientation = ORIENTATION_UNKNOWN;
            float X = -values[_DATA_X];
            float Y = -values[_DATA_Y];
            float Z = -values[_DATA_Z];

            /**
             * 这一段据说是 android源码里面拿出来的计算 屏幕旋转的 不懂 先留着 万一以后懂了呢
             */
            float magnitude = X * X + Y * Y;
            // Don't trust the angle if the magnitude is small compared to the y value
            if (magnitude * 4 >= Z * Z) {
                //屏幕旋转时
                float OneEightyOverPi = 57.29577957855f;
                float angle = (float) Math.atan2(-Y, X) * OneEightyOverPi;
                orientation = 90 - (int) Math.round(angle);
                // normalize to 0 - 359 range
                while (orientation >= 360) {
                    orientation -= 360;
                }
                while (orientation < 0) {
                    orientation += 360;
                }
            }

            if (orientation > 225 && orientation < 315) {  //横屏
                sensor_flag = false;
            } else if ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45)) {  //竖屏
                sensor_flag = true;
            }

            if (stretch_flag == sensor_flag) {  //点击变成横屏  屏幕 也转横屏 激活
                System.out.println("激活");
                sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);

            }
        }
    }

    private UMImage shareVideoImageUrl,sinaImageUrl;
    private String shareVideoUrl;
    private void sharesina() {
        ZiGeShareDialog dialog = new ZiGeShareDialog();
        dialog.setSharelister(zigeshareLister);
        dialog.show(getFragmentManager(), "dialog");

        if (TextUtils.isEmpty(videoTitle)) {
            videoTitle = "VR小伴马";
        }

        shareVideoUrl = UrlConsts.SHARE_VIDEIO_URL + jxVideoId;
        shareVideoImageUrl = new UMImage(ActivityVideodetailActivity.this, videoImageUrl);
        sinaImageUrl = new UMImage(ActivityVideodetailActivity.this, shareImageUrl);
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            com.umeng.socialize.utils.Log.d("plat", "platform" + platform);
            Toast.makeText(ActivityVideodetailActivity.this, " 分享成功啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(ActivityVideodetailActivity.this," 分享失败啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(ActivityVideodetailActivity.this," 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };


    private ZiGeShareDialog.ZigeshareLister zigeshareLister = new ZiGeShareDialog.ZigeshareLister() {
        @Override
        public void shareSina() {
            new ShareAction(ActivityVideodetailActivity.this).setPlatform(SHARE_MEDIA.SINA).setCallback(umShareListener)
                    .withTitle(videoTitle)
                    .withText("分享给大家一个好看的视频：")
                    .withMedia(sinaImageUrl)
                    .withTargetUrl(shareVideoUrl)
                    .share();
        }

        @Override
        public void shareWeiXin() {
            new ShareAction(ActivityVideodetailActivity.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                    .withTitle(videoTitle)
                    .withText("分享给大家一个好看的视频：")
                    .withMedia(shareVideoImageUrl)
                    .withTargetUrl(shareVideoUrl)
                    .share();
        }

        @Override
        public void shareWeiXinCircle() {
            new ShareAction(ActivityVideodetailActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                    .withTitle(videoTitle)
                    .withText("分享给大家一个好看的视频：")
                    .withMedia(shareVideoImageUrl)
                    .withTargetUrl(shareVideoUrl)
                    .share();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

}
